
import { login, getProfile, getUserByid } from '@/api/user'
import router from '@/router'
const state = {
  token: localStorage.getItem('rz-token') || '',
  profile: {}
}
const mutations = {
  setToken(state, data) {
    localStorage.setItem('rz-token', data)
    state.token = data
    console.log(data)
  },
  setProfile(state, data) {
    state.profile = data
    console.log(14, data)
  },
  removeToken(state) {
    state.token = ''
  },
  removeProfile(state) {
    state.profile = {}
  }
}
const actions = {
  async login(store, data) {
    const res = await login(data)
    // console.log(res)
    store.commit('setToken', res)

    localStorage.setItem('loginTime', Date.now())
  },
  async getProfile(store) {
    const res = await getProfile()
    const userInfo = await getUserByid(res.userId)
    store.commit('setProfile', {
      ...res,
      ...userInfo
    })
  },
  // 封装清除数据和跳转到登录页
  logout(store) {
    // 调用 清除 vux 中的token数据 的函数
    store.commit('removeToken')
    // 调用 清除 vux 中Profile数据 的函数
    store.commit('removeProfile')
    // 清除本地的 token
    localStorage.removeItem('rz-token')
    router.push('/login')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

